/*
 * @Descripttion: 处理header请求头辅助方法
 * @version:
 * @Author: yangzhihao
 * @Date: 2021-07-12 11:59:36
 * @LastEditors: yangzhihao
 * @LastEditTime: 2021-07-12 14:21:35
 */
import { isObject } from '.'
/**
 * @msg: 保证传入的大写Content-Type和小写一致
 * @param {any} headers 请求头
 * @param {string} normalizedName 头部名称
 * @return {*}
 */
function normalizeHearderName(headers: any, normalizedName: string): void {
  if (!headers) {
    return
  }
  Object.keys(headers).forEach(name => {
    if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
      headers[normalizedName] = headers[name]
      // 删除多余项
      delete headers[name]
    }
  })
}
export function processHeaders(headers: any, data: any): any {
  // 处理大小写问题
  normalizeHearderName(headers, 'Content-Type')
  // 如果data是纯对象格式，则需要添加content-type头
  if (isObject(data)) {
    if (headers && !headers['Content-Type']) {
      headers['Content-Type'] = 'application/json;charset=utf-8'
    }
  }
  return headers
}

export function parseHeaders(headers: string): any {
  let parsed = Object.create(null)
  // 判空
  if (!headers) {
    return parsed
  }
  headers.split('\r\n').forEach(line => {
    let [key, value] = line.split(':')
    // 去空格转小写
    key = key.trim().toLowerCase()

    if (!key) {
      return
    }
    if (value) {
      value = value.trim()
    }
    parsed[key] = value
  })
  return parsed
}
